import axios from "axios";
import { useStore } from "@/stores/userInfo";
import { ElMessage } from "element-plus";

//创建axios实例
const axiosInstance = axios.create({
    baseURL:"http://127.0.0.1:5150/",//网关5150
    timeout:100000,//等待时间  100s
});


//请求拦截器
axiosInstance.interceptors.request.use(
    (config) => {
      // 在请求发送之前做些什么
      // console.log("Request Interceptor:", config);
  
      const userStore = useStore();
      const token = userStore.userinfo.usertoken; // 获取token
      if (token) {
        config.headers["Authorization"] = `Bearer ${token}`; // 设置请求头
      }
  
      return config;
    },
    (error) => {
      // 对请求错误做些什么
      return Promise.reject(error);
    }
  );
  
  //响应拦截器
  axiosInstance.interceptors.response.use(
    (response) => {
      //如果请求失败的话
      if (!response.data.IsSuc) {
        console.log("请求失败", response);
        ElMessage.error(response.data.msg);
        return Promise.reject(new Error(response.data.msg));
      }
  
      return response;
    },
    (error) => {
      //处理不同状态码的错误请求
      const { response, message } = error;
  
      if (response) {
        switch (response.status) {
          case 401:
            ElMessage.error("未授权，请登录！");
            break;
          case 403:
            ElMessage.error("没有权限，禁止访问！");
            break;
          case 404:
            ElMessage.error("请求的资源不存在！");
            break;
          case 500:
            ElMessage.error("服务器内部错误！");
            break;
          default:
            ElMessage.error(`请求失败：${response.status}`);
        }
      } else {
        // 处理请求未响应的情况
        if (message.includes("timeout")) {
          ElMessage.error("请求超时，请稍后重试！");
        } else if (message.includes("Network Error")) {
          ElMessage.error("网络错误，请检查您的网络连接！");
        } else {
          ElMessage.error(`请求失败：${message}`);
        }
      }
  
      return Promise.reject(error);
    }
  );
  
  //导出axios实例
  export default axiosInstance;